package edu.hitwh.Repository;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.jpa.domain.Specification;
import jakarta.persistence.criteria.Predicate;
import edu.hitwh.entity.Transaction;

public class TransactionSpecifications {

    public static Specification<Transaction> getSpecification(TransactionQuery query) {
        return (root, cq, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (query.getStatus() != null) {
                predicates.add(cb.equal(root.get("status"), query.getStatus()));
            }

            if (query.getBorrowDateStart() != null) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("borrowDate"), query.getBorrowDateStart()));
            }

            if (query.getBorrowDateEnd() != null) {
                predicates.add(cb.lessThanOrEqualTo(root.get("borrowDate"), query.getBorrowDateEnd()));
            }

            if (query.getReturnDateStart() != null) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("returnDate"), query.getReturnDateStart()));
            }

            if (query.getReturnDateEnd() != null) {
                predicates.add(cb.lessThanOrEqualTo(root.get("returnDate"), query.getReturnDateEnd()));
            }

            if (query.getBorrowerName() != null) {
                predicates.add(cb.like(cb.lower(root.join("borrower").get("name")), "%" + query.getBorrowerName().toLowerCase() + "%"));
            }

            if (query.getBorrowerEmail() != null) {
                predicates.add(cb.like(cb.lower(root.join("borrower").get("email")), "%" + query.getBorrowerEmail().toLowerCase() + "%"));
            }

            if (query.getBookTitle() != null) {
                predicates.add(cb.like(cb.lower(root.join("book").get("title")), "%" + query.getBookTitle().toLowerCase() + "%"));
            }

            if (query.getBookAuthor() != null) {
                predicates.add(cb.like(cb.lower(root.join("book").get("author")), "%" + query.getBookAuthor().toLowerCase() + "%"));
            }

            if (query.getBookIsbn() != null) {
                predicates.add(cb.like(cb.lower(root.join("book").get("isbn")), "%" + query.getBookIsbn().toLowerCase() + "%"));
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }
}